package com.insmess.speech.common.util;

import org.apache.commons.io.IOUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.util.UUID;

public class InsmessFileUtils {
    /**
     * 根据MultipartFile获取临时文件File对象
     * @param file
     * @return
     * @throws IOException
     */
    public static File getTmpFile(MultipartFile file) throws IOException {
        //输出音频文件到本地
        File tmpDir = getTmpDir();
        File tmpAudioFile = new File(tmpDir, "source_" + UUID.randomUUID() + "_" + file.getOriginalFilename());
        OutputStream out = Files.newOutputStream(tmpAudioFile.toPath());
        InputStream in = file.getInputStream();
        IOUtils.copy(in, out);
        in.close();
        out.close();
        return tmpAudioFile;
    }

    /**
     * 获取临时目录对象
     * @return
     */
    public static File getTmpDir() {
        //创建临时存放的目录
        File tmpDir = new File("./tmp/audio");
        if (!tmpDir.exists()) {
            tmpDir.mkdirs();
        }
        return tmpDir;
    }

    public static void checkFormat(File file) {
        String[] formatArr = {".wav", ".m4a", "mp3"};
        String name = file.getName().toLowerCase();
        boolean flag = false;
        for (String format : formatArr) {
            if (name.endsWith(format)) {
                flag = true;
                break;
            }
        }
        if (!flag) {
            throw new RuntimeException("文件格式错误");
        }
    }
}
